"""
FastAPI Main Application Entry Point
"""
import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse

from app.core.config import settings
from app.core.database import engine, Base

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Lifespan events (startup and shutdown).
    """
    # --- Startup ---
    try:
        # 确保 Document 模型已被导入，以便 SQLModel/SQLAlchemy 能发现它并创建表
        from app.core import document  # noqa: F401
        
        logger.info("Initializing database tables...")
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)
        logger.info("Database tables initialized successfully")
    except Exception as e:
        # 数据库连接失败不应阻止应用启动（某些场景下）
        # 但在首次部署时通常需要。这里记录错误但允许继续，
        # 因为 uvicorn 会继续运行，后续请求可能会重试连接。
        logger.error(f"Database initialization failed: {e}")

    yield

    # --- Shutdown ---
    # Add cleanup code here if needed (e.g., closing connections)
    logger.info("Shutting down application...")

app = FastAPI(
    title=settings.APP_NAME,
    version="1.0.0",
    debug=settings.ENV == "development",
    lifespan=lifespan
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Update with specific domains in production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Import and include routers
try:
    from app.routers import rag
    app.include_router(rag.router)
    logger.info("RAG router registered successfully")
except ImportError as e:
    logger.error(f"Failed to import RAG router: {e}")
except Exception as e:
    logger.error(f"Failed to register router: {e}")

@app.get("/", response_class=HTMLResponse)
async def root():
    """Root path - File Upload UI"""
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Enterprise RAG System</title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; background: #f0f2f5; min-height: 100vh; display: flex; justify-content: center; align-items: center; padding: 20px; }
            .container { background: white; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); padding: 32px; max-width: 500px; width: 100%; }
            h1 { text-align: center; margin-bottom: 24px; color: #1a1a1a; }
            .upload-area { border: 2px dashed #d9d9d9; border-radius: 6px; padding: 32px; text-align: center; cursor: pointer; transition: border-color 0.3s; }
            .upload-area:hover { border-color: #1890ff; }
            .upload-icon { font-size: 32px; margin-bottom: 8px; }
            .upload-text { color: #666; }
            #fileInput { display: none; }
            .btn { width: 100%; background: #1890ff; color: white; border: none; padding: 12px; border-radius: 4px; font-size: 16px; font-weight: 500; cursor: pointer; margin-top: 16px; transition: background 0.3s; }
            .btn:hover { background: #40a9ff; }
            .btn:disabled { background: #d9d9d9; cursor: not-allowed; }
            .status { margin-top: 16px; padding: 8px 12px; border-radius: 4px; display: none; font-size: 14px; }
            .status.success { background: #f6ffed; border: 1px solid #b7eb8f; color: #52c41a; }
            .status.error { background: #fff1f0; border: 1px solid #ffa39e; color: #f5222d; }
            .status.info { background: #e6f7ff; border: 1px solid #91d5ff; color: #1890ff; }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>RAG Document Upload</h1>
            <div class="upload-area" id="uploadArea">
                <div class="upload-icon">📄</div>
                <div class="upload-text">Click or drag file to this area to upload</div>
            </div>
            <input type="file" id="fileInput">
            <button class="btn" id="uploadBtn" disabled>Upload</button>
            <div class="status" id="statusMsg"></div>
        </div>

        <script>
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');
            const uploadBtn = document.getElementById('uploadBtn');
            const statusMsg = document.getElementById('statusMsg');
            let selectedFile = null;

            uploadArea.addEventListener('click', () => fileInput.click());
            
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#1890ff';
            });

            uploadArea.addEventListener('dragleave', () => {
                uploadArea.style.borderColor = '#d9d9d9';
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#d9d9d9';
                if (e.dataTransfer.files.length) handleFile(e.dataTransfer.files[0]);
            });

            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length) handleFile(e.target.files[0]);
            });

            function handleFile(file) {
                selectedFile = file;
                uploadArea.innerHTML = `<div class="upload-icon">📄</div><div class="upload-text">${file.name}</div>`;
                uploadBtn.disabled = false;
                hideStatus();
            }

            function showStatus(msg, type) {
                statusMsg.textContent = msg;
                statusMsg.className = `status ${type}`;
                statusMsg.style.display = 'block';
            }

            function hideStatus() {
                statusMsg.style.display = 'none';
            }

            uploadBtn.addEventListener('click', async () => {
                if (!selectedFile) return;
                
                uploadBtn.disabled = true;
                uploadBtn.textContent = 'Uploading...';
                showStatus('Uploading...', 'info');

                const formData = new FormData();
                formData.append('file', selectedFile);

                try {
                    const res = await fetch('/api/v1/documents', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const data = await res.json();
                    
                    if (res.ok) {
                        showStatus(`Success! ID: ${data.id}`, 'success');
                        uploadBtn.textContent = 'Uploaded';
                        setTimeout(() => {
                            uploadBtn.textContent = 'Upload';
                            uploadBtn.disabled = true;
                            uploadArea.innerHTML = `<div class="upload-icon">📄</div><div class="upload-text">Click or drag file to this area to upload</div>`;
                            selectedFile = null;
                        }, 3000);
                    } else {
                        showStatus(`Error: ${data.detail || 'Upload failed'}`, 'error');
                        uploadBtn.disabled = false;
                        uploadBtn.textContent = 'Upload';
                    }
                } catch (err) {
                    showStatus(`Error: ${err.message}`, 'error');
                    uploadBtn.disabled = false;
                    uploadBtn.textContent = 'Upload';
                }
            });
        </script>
    </body>
    </html>
    """
    return HTMLResponse(content=html_content)

@app.get("/health")
async def health_check():
    return {"status": "healthy"}
